package com.example.demo8;

import javafx.animation.AnimationTimer;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.input.KeyCode;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;

import java.util.List;

public class RPGgame extends Application {
    // 游戏常量
    public static final int WIDTH = 1555;
    public static final int HEIGHT = 972;
    public static final int TILE_SIZE = 40;
    public static final int PLAYER_SIZE = 30;
    public static final int PROJECTILE_SIZE = 8;

    private GameController gameController;
    private Stage primaryStage;
    private StartScreen startScreen;
    private Canvas canvas;
    private GraphicsContext gc;
    private AnimationTimer gameLoop;
    private Scene gameScene;               // 保存游戏场景（方便切换回游戏）
    private EquipmentShopScreen shopScreen; // 商店界面实例
    private boolean isShopOpen = false;     // 是否处于商店界面（默认关闭）
    private Map map;

    @Override
    public void start(Stage primaryStage) {
        this.primaryStage = primaryStage;
        primaryStage.setTitle("美少女RPG冒险游戏");

        startScreen = new StartScreen(
                () -> switchToHeroSelection(false),
                () -> switchToHeroSelection(true)
        );

        primaryStage.setScene(startScreen.getScene());
        primaryStage.setResizable(false);
        primaryStage.show();
    }

    private void switchToHeroSelection(boolean twoPlayerMode) {
        // 创建英雄选择界面
        HeroSelectionUI heroSelectionUI = new HeroSelectionUI(twoPlayerMode);
        Scene heroSelectionScene = new Scene(heroSelectionUI.getRoot(), 1555, 973);

        // 设置选择英雄后的回调
        heroSelectionUI.setOnHeroSelected(selectedHeroes -> {
            // 当英雄选择完成后，启动游戏
            startGame(twoPlayerMode, selectedHeroes);
        });

        primaryStage.setScene(heroSelectionScene);
    }

    private void startGame(boolean twoPlayerMode, List<Hero> selectedHeroes) {
        if (gameLoop != null) {
            gameLoop.stop();
        }
        // 初始化 GameController
        canvas = new Canvas(WIDTH, HEIGHT);
        gc = canvas.getGraphicsContext2D();
        map = new Map(canvas);
        gameController = new GameController(twoPlayerMode, selectedHeroes, map);

        Pane root = new Pane();
        root.getChildren().add(canvas);

        gameScene = new Scene(root, WIDTH, HEIGHT);
        setupInputHandlers(gameScene);
        primaryStage.setScene(gameScene);

        // ------------------- 新增：初始化商店界面 -------------------
        shopScreen = new EquipmentShopScreen(); // 创建商店实例
        Scene shopScene = shopScreen.getScene(); // 获取商店场景

        // 给商店场景添加B键监听：按下B键退出商店
        shopScene.setOnKeyPressed(e -> {
            if (e.getCode() == KeyCode.B) {
                closeShop(); // 调用退出商店的方法
            }
        });

        gameLoop = new AnimationTimer() {
            @Override
            public void handle(long now) {
                update();
                render();
            }
        };
        gameLoop.start();
    }

    private void update() {
        if (gameController.isGameOver() || gameController.isGameWin()) return;

        gameController.update();  // 更新游戏逻辑
    }

    private void render() {
        gc.clearRect(0, 0, WIDTH, HEIGHT);
        gc.setFill(javafx.scene.paint.Color.BLACK);
        gc.fillRect(0, 0, WIDTH, HEIGHT);
        map.drawMap(gc);
        // 绘制游戏对象
        gameController.render(gc); // 渲染游戏元素
    }

    private void setupInputHandlers(Scene scene) {
        scene.setOnKeyPressed(e -> {
            if (gameController.isGameOver() || gameController.isGameWin()) {
                if (e.getCode() == KeyCode.R) resetGame();
                return;
            }

            // ------------------- 新增：处理B键打开商店 -------------------
            if (e.getCode() == KeyCode.B) {
                openShop(); // 按下B键，打开商店
                return;     // 不将B键事件传递给游戏控制器（避免冲突）
            }

            map.handleKeyPressed(e.getCode());
            gameController.handleInput(e.getCode(), true); // 按下时，传递输入状态
        });

        scene.setOnKeyReleased(e -> {
            gameController.handleInput(e.getCode(), false);  // 释放时，更新控制状态
        });
    }

    private void resetGame() {
        switchToHeroSelection(false);  // 重新开始游戏
    }

    /**
     * 打开商店：切换到商店场景，暂停游戏循环
     */
    private void openShop() {
        if (!isShopOpen) {
            isShopOpen = true;               // 标记为商店已打开
            gameLoop.stop();                 // 暂停游戏循环（停止更新游戏逻辑）
            primaryStage.setScene(shopScreen.getScene()); // 切换到商店场景
        }
    }

    /**
     * 关闭商店：切换回游戏场景，继续游戏循环
     */
    private void closeShop() {
        if (isShopOpen) {
            isShopOpen = false;              // 标记为商店已关闭
            primaryStage.setScene(gameScene); // 切换回游戏场景
            gameLoop.start();                // 继续游戏循环（恢复更新游戏逻辑）
        }
    }

    public static void main(String[] args) {
        launch(args);
    }
}